var express = require('express');
var router = express.Router();
var db = require('../my_modules/my_sequlize');
var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var conf = require('../config');
var e = require('../my_modules/error');
var torrent = require('../my_modules/torrent_client');

/* GET users listing. */
router.get('/', function(req, res) {
  res.send('respond with a resource');
});

router.post('/login', function (req, res) {
  db.user.find({
      where: {
          username: req.body.username || '1',
          password: crypto.createHash('sha1').update(req.body.password || '1').digest('hex')
      }
  }).then(function (msg) {
      if(msg) {
          req.session.userId = msg.id;
          req.session.username = msg.username;
          req.session.root = path.join(path.resolve(conf.file.root),req.session.username);
          req.session.dir = '/';
          if(!fs.existsSync(path.resolve(conf.file.root))) fs.mkdirSync(path.resolve(conf.file.root))
          if(!fs.existsSync(req.session.root)) fs.mkdirSync(req.session.root);
          res.json(e.success);
      } else res.json(e.passwordErr);
  })
});

router.get('/logout', function (req, res) {
    req.session.userId = null;
    req.session.username = null;
    res.redirect('/');
});

setTimeout(function () {
    db.user.count().then(function (c) {
        if(!c) {
            db.user.create({
                username: 'lmn',
                password: crypto.createHash('sha1').update('111111').digest('hex')
            })
        }
    })
},1000);
module.exports = router;
